package com.common.www.controller.auth;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.service.auth.TokenService;
import com.common.www.service.auth.UserService;
import com.common.www.service.file.FileService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.auth.AuthUser;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.redis.lock.LockUtil;
import com.common.www.utils.Md5Utils;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.TxtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import static com.common.www.redis.lock.LockName.UPDATE_USER;

@RestController
@CrossOrigin()
@Api(tags = "MGT 用户相关接口")
@RequestMapping(value = {"/mgt/auth/user/"})
public class MGTUserController extends DefaultCrudController<AuthUser, String> {

    @Autowired
    private UserService userService;
    @Autowired
    TokenService tokenService;
    @Autowired
    FileService fileService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected IBaseService getService() {
        return userService;
    }

    @ApiOperation("添加用户的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        AuthUser authUser = JSON.parseObject(json, AuthUser.class);
        boolean getLock = false;
        String key = UPDATE_USER.toString();
        try {
            getLock = LockUtil.tryLock(key, 10, 5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (!getLock) {//未抢到
            return R.fail("获取锁失败");
        }
        if (TxtUtil.isEmpty(authUser.getId())) {//新增用户
//            authUser.setCreator(GlobalSessionUtils.getUserId());
            //验证用户名是否已存在
            if (userService.isHadUsername(authUser.getUsername())) {
                LockUtil.unlock(key);
                return R.fail("用户名已存在，请重新设置");
            }
            //验证电话是否已存在
            if (userService.isHadPhone(authUser.getPhone())) {
                LockUtil.unlock(key);
                return R.fail("电话已存在，请重新设置");
            }
            String password = passwordEncoder.encode(Md5Utils.MD5Encode(authUser.getPassword()));
            authUser.setCreator("系统");
            authUser.setFlag(1);
            authUser.setStatus(0);
            authUser.setPassword(password);
        } else {//修改用户信息
            AuthUser localAuthUser = userService.findOne(authUser.getId());
            if (localAuthUser == null) {
                LockUtil.unlock(key);
                return R.fail("修改用户不存在");
            }
            //如果修改了用户名
            if (!TxtUtil.isEmpty(authUser.getUsername()) && !authUser.getUsername().equals(localAuthUser.getUsername())) {
                //验证用户名是否已存在
                if (userService.isHadUsername(authUser.getUsername())) {
                    LockUtil.unlock(key);
                    return R.fail("用户名已存在，请重新设置");
                }
            }
            //如果修改了手机号
            if (!TxtUtil.isEmpty(authUser.getPhone()) && !authUser.getPhone().equals(localAuthUser.getPhone())) {
                //验证电话是否已存在
                if (userService.isHadPhone(authUser.getPhone())) {
                    LockUtil.unlock(key);
                    return R.fail("电话已存在，请重新设置");
                }
            }

            if (!TxtUtil.isEmpty(authUser.getPassword()) &&
                    !authUser.getPassword().equals(localAuthUser.getPassword())) {//如果存储的密码和修改的密码不一样就重新修改密码
                String password = passwordEncoder.encode(Md5Utils.MD5Encode(authUser.getPassword()));
                authUser.setPassword(password);
            }
        }
        if (authUser.getGender() == null) {
            authUser.setGender(0);
        }
//        if (authUser.getProvinceCity() != null) {
//            authUser.setCode(authUser.getProvinceCity().getCode());
//        }
        authUser = userService.save(authUser);
        LockUtil.unlock(key);
        return R.ok(authUser);
    }

    @Override
    public Result<List<AuthUser>> all() {
        return super.all();
    }

    @ApiOperation("批量冻结解冻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.锁定 2.解锁", defaultValue = ""),
    })
    @RequestMapping(value = "/batchLock", method = RequestMethod.POST)
    public Result batchLock(String[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            AuthUser authUser = userService.findOne(ids[i]);
            if (authUser != null) {
                if (operate == 1) {
                    authUser.setLocked(true);
                } else if (operate == 2) {
                    authUser.setLocked(false);
                }
                userService.save(authUser);
            }
        }
        return R.ok();
    }

    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(String[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            AuthUser authUser = userService.findOne(ids[i]);
            if (authUser != null) {
                if (operate == 1) {
                    authUser.setFlag(0);
                } else if (operate == 2) {
                    authUser.setFlag(1);
                }
                userService.save(authUser);
            }
        }
        return R.ok();
    }

}
